<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      ref="deptFrom"
      label-width="120px"
      :model="fromData"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="fromData.name"
          style="width: 80%"
          placeholder="1-10个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="fromData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="fromData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeesSimple"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="fromData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="space-between">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOk">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeesSimple } from '@/api/employees'
export default {
  name: 'Popups',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    // 当前节点数据
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    // 部门名查重
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.fromData.id) {
        // 编辑 。 先找同级再找重复 当前部门的name不能与其他的同级部门重复，可以和自己的名字重复 filter返回所有匹配数据的对象some方法返回一个布尔值
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.treeNode.id).some(item => item.name === value)
      } else {
        // 新增
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
        // 根据获取的数据对传入的value进行判重，
      }
      isRepeat ? callback(new Error(`同级部门下已存在${value}`)) : callback()
    }
    // 部门编码查重
    const checkCoedRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.fromData.id) {
        // 编辑,编码不能和所有的其他部门重复，所以只用排除自己
        isRepeat = depts.filter(item => item.id !== this.treeNode.id).some(item => item.code === value && value !== '')
      } else {
        // 新增
        isRepeat = depts.some(item => item.code === value && value !== '')
      }
      isRepeat ? callback(new Error(`组织结构下已经存在${value}编码`)) : callback()
    }

    return {
      fromData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '部门名称长度为1~10个字符', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码长度为1~50个字符', trigger: 'blur' },
          { validator: checkCoedRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门负责人长度为1~50个字符', trigger: 'blur' }

        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍长度为1~300个字符', trigger: 'blur' }

        ]
      },
      peoples: []
    }
  },
  computed: {
    // 使用当前表单是否存在id,编辑部门时会获取部门信息会传递部门ID
    showTitle() {
      return this.fromData.id ? '编辑部门' : '新增部门'
    }
  },
  watch: {},
  created() { },
  mounted() { },
  methods: {
    async getEmployeesSimple() {
      this.peoples = await getEmployeesSimple()
      console.log(this.peoples)
    },
    async getDepartDetail(id) {
      this.fromData = await getDepartDetail(id)
    },
    btnOk() {
      this.$refs.deptFrom.validate(async isOk => {
        if (isOk) {
          if (this.fromData.id) {
            // 编辑
            await updateDepartments(this.fromData)
          } else {
            // 新增
            await addDepartments({ ...this.fromData, pid: this.treeNode.id })
          }
          this.$emit('addDepts')
          // 这里使用 sync 修饰符进行传递
          this.$emit('update:showDialog', false)
        }
      })
    },
    btnCancel() {
      // 这里重置表单是因为在title判定时用到的iD不会在 ref重置
      this.fromData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$emit('update:showDialog', false)
      // 重置表单
      this.$refs.deptFrom.resetFields()
    }
  }
}
</script>

<style scoped></style>
